package com.zxd.interview.eightthread.threadsafeerror;

import java.time.DayOfWeek;
import java.util.HashMap;
import java.util.Map;

/**
 * 线程安全问题，不正确的发布对象
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.threadsafeerror
 * @Description : 线程安全问题，不正确的发布对象
 * @Create on : 2023/3/28 12:47
 **/
public class ThreadSafeErrorThree {

    private Map<String, Object> param = new HashMap<>();

    ThreadSafeErrorThree(){
        param.put("SUNDAY", DayOfWeek.SUNDAY);
        param.put("MONDAY", DayOfWeek.MONDAY);
        param.put("TUESDAY", DayOfWeek.TUESDAY);
        param.put("WEDNESDAY", DayOfWeek.WEDNESDAY);
        param.put("SATURDAY", DayOfWeek.SATURDAY);
    }

    public Map<String, Object> getMap(){
        return param;
    }
    public Map<String, Object> getMapImproved(){
        return new HashMap<>(param);
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSafeErrorThree threadSafeErrorThree = new ThreadSafeErrorThree();
        // 线程不安全的访问方式
//        Map<String, Object> map = threadSafeErrorThree.getMap();
        // 线程安全的访问方式
        Map<String, Object> map = threadSafeErrorThree.getMapImproved();
        map.remove("MONDAY");
        map.remove("SATURDAY");
        System.out.println(map);
        new Thread(() -> {
            // 线程不安全的访问方式
//            Map<String, Object> maps = threadSafeErrorThree.getMap();
            // 线程安全的访问方式
            Map<String, Object> maps = threadSafeErrorThree.getMapImproved();
            Object monday = maps.get("MONDAY");
            System.out.println(monday);
        }).start();

    }/**
     错误的发布对象
     {WEDNESDAY=WEDNESDAY, SUNDAY=SUNDAY, TUESDAY=TUESDAY}
     null

     使用getMapImproved 之后
     {SUNDAY=SUNDAY, WEDNESDAY=WEDNESDAY, TUESDAY=TUESDAY}
     MONDAY
     */
}
